#!/usr/bin/env node
"use strict";

const fs = require("fs");
const path = require("path");

const INPUT_PATH = path.join(__dirname, "test.txt");

/**
 * Evenly split text content into 5 parts.
 * If it cannot be evenly divided, earlier parts get +1 char until remainder is exhausted.
 * @param {string} text
 * @returns {string[]}
 */
function splitIntoFive(text) {
  const PARTS = 5;
  const totalLength = typeof text === "string" ? text.length : 0;
  const base = Math.floor(totalLength / PARTS);
  const remainder = totalLength % PARTS;
  const chunks = [];
  let offset = 0;
  for (let i = 0; i < PARTS; i++) {
    const size = base + (i < remainder ? 1 : 0);
    const piece = text.slice(offset, offset + size);
    chunks.push(piece);
    offset += size;
  }
  return chunks;
}

function main() {
  if (!fs.existsSync(INPUT_PATH)) {
    console.error("找不到 test.txt，请先生成或放置在同目录下。");
    process.exit(1);
  }

  const content = fs.readFileSync(INPUT_PATH, "utf8");
  const parts = splitIntoFive(content);

  parts.forEach((part, index) => {
    const outFile = path.join(__dirname, `test.part${index + 1}.txt`);
    fs.writeFileSync(outFile, part, "utf8");
  });
}

if (require.main === module) {
  main();
}

module.exports = splitIntoFive;


